import * as echarts from '../ec-canvas/echarts';

function initChart(canvas, width, height, dpr, context) {
  try {
    const chart = echarts.init(canvas, null, {
      width: width,
      height: height,
      devicePixelRatio: dpr
    });
    
    console.log('Chart instance created:', chart);
    canvas.setChart(chart);

    // 从组件实例获取配置数据
    const { title, xAxisData, yAxisData, xAxisName, yAxisName, lineColor, step } = context.data;

    var option = {
      title: {
        text: title || '折线图',
        left: 'center',
        top: '5%',
        textStyle: {
          color: '#333',
          fontSize: 14
        }
      },
      grid: {
        left: '15%',
        right: '10%',
        top: '20%',
        bottom: '20%',
        containLabel: true
      },
      tooltip: {
        show: true,
        trigger: 'axis',
        backgroundColor: 'rgba(0,0,0,0.8)',
        textStyle: {
          color: 'white'
        }
      },
      xAxis: {
        name: xAxisName || "X轴",
        nameLocation: 'middle',
        nameGap: 25,
        type: 'category',
        boundaryGap: false,
        data: xAxisData || [],
        axisLine: {
          lineStyle: {
            color: 'black'
          }
        },
        axisLabel: {
          color: 'black',
          fontSize: 10
        }
      },
      yAxis: {
        name: yAxisName || "Y轴",
        nameLocation: 'middle',
        nameGap: 35,
        type: 'value',
        axisLine: {
          show: true,
          lineStyle: {
            color: 'black'
          }
        },
        axisLabel: {
          color: 'black',
          fontSize: 10
        },
        splitLine: {
          lineStyle: {
            type: 'dashed',
            color: 'black'
          }
        }
      },
      series: [{
        name: yAxisName || 'Y轴数据',
        type: 'line',
        ...(step && { step: step }),
        smooth: false,
        lineStyle: {
          width: 3,
          color: lineColor || '#ce1b28',
          shadowColor: `rgba(${lineColor ? hexToRgb(lineColor).join(',') : '206, 27, 40'}, 0.3)`,
          shadowBlur: 10,
          shadowOffsetY: 8
        },
        itemStyle: {
          color: lineColor || '#ce1b28'
        },
        // TODO 确认是否需要展示
        label: {
          show: false,
          position: 'top',
          textStyle: {
            color: 'blue',
            fontSize: 10
          }
        },
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [{
              offset: 0, color: `rgba(${lineColor ? hexToRgb(lineColor).join(',') : '206, 27, 40'}, 0.3)`
            }, {
              offset: 1, color: `rgba(${lineColor ? hexToRgb(lineColor).join(',') : '206, 27, 40'}, 0.1)`
            }]
          }
        },
        data: yAxisData || []
      }]
    };

    console.log('Setting chart option:', option);
    chart.setOption(option);
    console.log('Chart initialized successfully');
    
    // 通知组件图表初始化成功
    context.setData({
      chartInitialized: true,
      canvasWidth: width,
      canvasHeight: height
    });
    
    return chart;
  } catch (error) {
    console.error('Error initializing chart:', error);
    
    // 通知组件图表初始化失败
    context.setData({
      chartInitialized: false,
      initError: error.message
    });
    
    return null;
  }
}

// 辅助函数：将十六进制颜色转换为RGB
function hexToRgb(hex) {
  const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
  return result ? [
    parseInt(result[1], 16),
    parseInt(result[2], 16),
    parseInt(result[3], 16)
  ] : [206, 27, 40]; // 默认颜色
}

Component({
  properties: {
    // 图表标题
    title: {
      type: String,
      value: '折线图'
    },
    // X轴数据
    xAxisData: {
      type: Array,
      value: []
    },
    // Y轴数据
    yAxisData: {
      type: Array,
      value: []
    },
    // X轴描述
    xAxisName: {
      type: String,
      value: 'X轴'
    },
    // Y轴描述
    yAxisName: {
      type: String,
      value: 'Y轴'
    },
    // 折线颜色
    lineColor: {
      type: String,
      value: '#ce1b28'
    },
    // 步进模式：start/middle/end 或空字符串
    step: {
      type: String,
      value: ''
    },
    // 图表高度
    chartHeight: {
      type: String,
      value: '600rpx'
    },
    // 是否显示调试信息
    showDebug: {
      type: Boolean,
      value: false
    },
    id: {
      type: String,
      value: 'line-chart-canvas'
    }
  },

  data: {
    ec: {},
    chartInitialized: false,
    canvasWidth: 0,
    canvasHeight: 0,
    initError: null
  },

  lifetimes: {
    attached() {
      console.log('LineChart component attached');
      // 绑定初始化函数，传递组件实例上下文
      this.setData({
        ec: {
          onInit: (canvas, width, height, dpr) => initChart(canvas, width, height, dpr, this)
        }
      });
    },
    
    ready() {
      console.log('LineChart component ready');
      console.log('Properties:', this.properties);
    }
  },

  methods: {
    // 更新图表数据
    updateChart(newData) {
      const { xAxisData, yAxisData, title, xAxisName, yAxisName, lineColor, step } = newData;
      
      // 更新组件数据
      const updateData = {};
      if (xAxisData !== undefined) updateData.xAxisData = xAxisData;
      if (yAxisData !== undefined) updateData.yAxisData = yAxisData;
      if (title !== undefined) updateData.title = title;
      if (xAxisName !== undefined) updateData.xAxisName = xAxisName;
      if (yAxisName !== undefined) updateData.yAxisName = yAxisName;
      if (lineColor !== undefined) updateData.lineColor = lineColor;
      if (step !== undefined) updateData.step = step;
      
      this.setData(updateData);
      
      // 重新初始化图表
      this.setData({
        ec: {
          onInit: (canvas, width, height, dpr) => initChart(canvas, width, height, dpr, this)
        }
      });
    },

    // 获取图表实例（如果需要的话）
    getChartInstance() {
      return this.chart;
    },

    // 保存图表为图片
    saveToImage() {
      return new Promise((resolve, reject) => {
        // 获取内部的 ec-canvas 组件
        const ecComponent = this.selectComponent(`#${this.data.id}`);
        
        if (!ecComponent) {
          const error = '无法找到 ec-canvas 组件';
          console.error(error);
          reject(new Error(error));
          return;
        }

        // 调用 ec-canvas 的保存方法
        ecComponent.canvasToTempFilePath({
          success: res => {
            console.log("图表保存成功，临时文件路径:", res.tempFilePath);
            resolve(res.tempFilePath);
          },
          fail: err => {
            console.error('生成图片失败:', err);
            reject(err);
          }
        });
      });
    }
  }
}); 